import time
import aiohttp
import requests
from requests.exceptions import RequestException
from common_tools.tools_common import OtherTools
from app.hgcm_spider_config.hgcm_spider_config import WeChatHookUrl, WeChatHookAuthorization
import threading


class WeChatROBOTEvent:
    def __init__(self):
        self.post_url = WeChatHookUrl
        self.header = self.comm_header()
        self.ot = OtherTools()
        self.last_request_time = 0  # 记录上次请求时间戳

    @staticmethod
    def comm_header():
        return {"Authorization": WeChatHookAuthorization}

    # 公用请求POST
    async def post_response_wechat_client(self, payload):
        lock = threading.Lock()
        condition = threading.Condition(lock)
        timeout = aiohttp.ClientTimeout(total=10)  # 设置超时时间为10秒
        with condition:
            condition.wait(timeout=5)  # 设置超时时间为5秒 也就是10秒内最多发1条消息
            async with aiohttp.ClientSession(timeout=timeout) as session:
                try:
                    async with session.post(self.post_url, headers=self.header, json=payload) as response:
                        return await response.json()
                except:
                    self.ot.send_mail('采集系统发送到微信群失败或采集或者微信号失败')

    # 公用请求GET
    async def get_response_wechat_client(self, payload):
        async with aiohttp.ClientSession() as session:
            async with session.get(self.post_url, headers=self.header, json=payload) as response:
                try:
                    res = await response.json()
                except:
                    res = None
            if res:
                return
            async with session.get(self.post_url_bak, headers=self.header, json=payload) as response:
                try:
                    await response.json()
                except:
                    pass

    async def sent_text(self, user, msg):
        payload = {"api": 2200, "data": {"content": msg, "userName": user}}
        return await self.post_response_wechat_client(payload)

    # # 公用请求POST
    # def post_response_wechat_client_sync(self, payload):
    #     """同步版本的微信客户端请求方法"""
    #
    #     # 控制请求频率：确保每10秒内最多发送1条消息
    #     current_time = time.time()
    #     if current_time - self.last_request_time < 5:
    #         # 如果距离上次请求不足5秒，等待剩余时间
    #         wait_time = 5 - (current_time - self.last_request_time)
    #         time.sleep(wait_time)
    #
    #     self.last_request_time = current_time  # 更新最后请求时间
    #
    #     try:
    #         # 发送同步POST请求，设置10秒超时
    #         response = requests.post(
    #             self.post_url,
    #             headers=self.header,
    #             json=payload,
    #             timeout=10  # 总超时时间（包含连接、传输等）
    #         )
    #
    #         # 检查HTTP响应状态码
    #         response.raise_for_status()
    #
    #         return response.json()
    #
    #     except RequestException as e:
    #         # 处理所有请求异常
    #         error_msg = f"微信请求失败: {str(e)}"
    #         self.ot.send_mail(error_msg)
    #         return None
    #
    #

    # 公用请求POST
    def post_response_wechat_client_sync(self, payload):
        """同步版本的微信客户端请求方法"""

        # 控制请求频率：确保每10秒内最多发送1条消息
        current_time = time.time()
        if current_time - self.last_request_time < 5:
            # 如果距离上次请求不足5秒，等待剩余时间
            wait_time = 5 - (current_time - self.last_request_time)
            time.sleep(wait_time)

        self.last_request_time = current_time  # 更新最后请求时间

        try:
            # 发送同步POST请求，设置10秒超时
            response = requests.post(
                self.post_url,
                headers=self.header,
                json=payload,
                timeout=10  # 总超时时间（包含连接、传输等）
            )

            # 检查HTTP响应状态码
            response.raise_for_status()

            return response.json()

        except RequestException as e:
            # 处理所有请求异常
            error_msg = f"微信请求失败: {str(e)}"
            self.ot.send_mail(error_msg)
            return None
